const serveStatic = require('serve-static')
const http = require('http')
const path = require('path')
const fs = require('fs')

const resolve = p => path.resolve(__dirname, p)

const port = +process.env.PORT || 3000
// Serve up public/ftp folder
const serve = serveStatic(resolve('dist'), {
  index: ['index.html'],
  fallthrough: true
})
 
// Create server
const server = http.createServer((req, res) => {
  // eslint-disable-next-line no-console
  console.log(`${req.method} ${req.url}`)
  serve(req, res, function () {
    fs.readFile(resolve('dist/index.html'), { encoding:'utf-8' }, function (err, text) {
      if (err) {
        res.statusCode = 500
        res.statusMessage = err.message
        res.end()
      } else {
        res.setHeader('Content-Type', 'text/html; chartset=utf-8')
        res.end(text)
      }
    })
  })
})
 
// Listen
server.listen(port, () => {
  // eslint-disable-next-line no-console
  console.log('Running on ' + port)
})
